/**************************
 ***	ImageFields.c	***
 *************************/

#include "ImageType/ImageType.h"



void
image_to_fields( image_type *sim, image_type **oddField, image_type **evenField )
{
u_int	*sp,	*p1,	*p2;
int	evenRow,	oddRow;
int	i,	j;


	if( sim->row % 2 == 0 )
		evenRow = oddRow = sim->row / 2;
	else {
		evenRow = sim->row / 2;
		oddRow = evenRow + 1;
	}

	*oddField = image_create( oddRow, sim->column, 4, 1, NULL );
	*evenField = image_create( evenRow, sim->column, 4, 1, NULL );

	sp = (u_int *)sim->data;
	p1 = (u_int *)(*oddField)->data;
	p2 = (u_int *)(*evenField)->data;
	
/*
	for( i = 0 ; i < sim->row ; i++ ) {
		if( i % 2 == 0 ) {
			for( j = 0 ; j < sim->column ; j++ )
				*p1++ = *sp++;
		}
		else {
			for( j = 0 ; j < sim->column ; j++ )
				*p2++ = *sp++;
		}	
	}
*/
	for( i = 0 ; i < sim->row ; i += 2 ) {

		for( j = 0 ; j < sim->column ; j++ )
			*p1++ = *sp++;


		for( j = 0 ; j < sim->column ; j++ )
			*p2++ = *sp++;
	}
}


image_type *
image_from_fields( image_type *oddField, image_type *evenField )
{
image_type *im;
u_int	*tp,	*p1,	*p2;
int	row;
int	i,	j;

	
	row = evenField->row + oddField->row;

	im = image_create( row, evenField->column, 4, 1, NULL );

	tp = (u_int *)im->data;
	p1 = (u_int *)oddField->data;
	p2 = (u_int *)evenField->data;

	for( i = 0 ; i < im->row ; i++ ) {
		if( i % 2 == 0 ) {
			for( j = 0 ; j < im->column ; j++ )
				*tp++ = *p1++;
		}
		else {
			for( j = 0 ; j < im->column ; j++ )
				*tp++ = *p2++;
		}		
	}
	return( im );
}




image_type *
image_field( image_type *sim, int field, int half )
{
image_type	*im;
u_int	*sp,	*p;
int	row,	col;
int	i,	j;

	if( half == 1 )
		return( image_field_half( sim, field ) );



	row = sim->row/2;
	col = sim->column;

	im = image_create( row, col, 4, 1, NULL );


	sp = (u_int *)sim->data;
	p = (u_int *)(im)->data;

	
	if( field == 2 )
		sp += sim->column;
	
	for( i = 0 ; i < sim->row ; i += 2, sp += sim->column ) {

		for( j = 0 ; j < sim->column ; j++ )
			*p++ = *sp++;
	}

	return( im );
}


image_type *
image_field_half( image_type *sim, int field )
{
image_type	*im;
u_int	*sp,	*p;
int	row,	col;
int	i,	j;
int	red,	green,	blue;


	row = sim->row/2;
	col = sim->column/2;

	im = image_create( row, col, 4, 1, NULL );


	sp = (u_int *)sim->data;
	p = (u_int *)(im)->data;

	
	if( field == 2 )
		sp += sim->column;
	
	for( i = 0 ; i < sim->row ; i += 2, sp += sim->column ) {

		for( j = 0 ; j < sim->column ; j += 2 ){
			red = (IMAGE4_RED(*sp) + IMAGE4_RED(*(sp+1)) )/2;
			green = (IMAGE4_GREEN(*sp) + IMAGE4_GREEN(*(sp+1)) )/2;
			blue = (IMAGE4_BLUE(*sp) + IMAGE4_BLUE(*(sp+1)) )/2;
			*p++ = IMAGE4_RGB( red, green, blue );

			sp += 2;
		}
	}

	return( im );
}